//
//  FirstViewController.m
//  shouji138
//
//  Created by administrator on 8/27/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "FirstViewController.h"
#import "bestappAppDelegate.h"
#import "regex.h"

@implementation FirstViewController


-(IBAction)buttonClick:(id)sender{
	
	//clock the click button function;
	//if([[SrnStudentAppDelegate App] getJoinClicked] == NO)
	{
		//[[SrnStudentAppDelegate App] setJoinClicked:YES];
		
		if([self doValidation]==NO)
		{
			return nil;
		}
		
		//get ip.
		
		NSString *server = serveraddress.text;
		[[NSUserDefaults standardUserDefaults] setObject: server forKey: @"host_setting"];
		//[SrnStudentAppDelegate App].ip = serverip;
		
		//get port.
		NSString *user = username.text;
		[[NSUserDefaults standardUserDefaults] setObject: user forKey: @"id_setting"];
		
		//get connection limit.
		NSString *pass = password.text;
		
		//startlisten.
		[[NSUserDefaults standardUserDefaults] setObject: pass forKey: @"password_setting"];
			
		bestappAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
		[appDelegate init];
		
		//remove subviews
		
	}
		
}

-(BOOL)doValidation
{
	if([self isValidIPAddress:serveraddress.text] == NO)
	{
		
		[self showAlertView:@"Empty or Invalid Server Address!"];
		serveraddress.text = @"";
		return NO;
	}
	
	if([self isValidPort:username.text] == NO)
	{
		
		[self showAlertView:@"Empty or Invalid Username!"];
		username.text = @"";
		return NO;
	}
	
	if([self isValidName:password.text] == NO)
	{
		[self showAlertView:@"Empty password!"];
		password.text = @"";
		return NO;
	}
	return YES;
}

-(BOOL)RegExpMatch:(NSString *)string withPattern:(NSString*)pattern{
    regex_t reg;
    regmatch_t sub[10];
    int status=regcomp(&reg, [pattern UTF8String], REG_EXTENDED);
    if(status)return NO;
    status=regexec(&reg, [string UTF8String], 10, sub, 0);
    if(status==REG_NOMATCH)return NO;
    else if(status)return NO;
    return YES;
}

-(void)showAlertView:(NSString *)comment
{
	alertView = [[UIAlertView alloc] initWithTitle: @"Input Error" message:comment 
			delegate:self cancelButtonTitle:nil 
			otherButtonTitles:@"OK",nil];
	
    [alertView show];
	[alertView release];
	
}

//Decide whether the ip address is valid or not;
-(BOOL)isValidIPAddress:(NSString *)theIP
{
	return YES;
}



//Decide whether the Port is valid or not;
-(BOOL)isValidPort:(NSString *)thePort
{
	return YES;
}


//Decide whether the Name is valid or not;
-(BOOL)isValidName:(NSString *)theName
{
	return YES;
}


/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	keyboardShown = NO;
	
	NSString *server = [[NSUserDefaults standardUserDefaults] stringForKey: @"host_setting"];
	if(!server){
		//server = @"mail.nicesms.cn";
	}
	serveraddress.text = server;
	
	NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey: @"id_setting"];
	if(!user){
		//user = @"sevenearly";
	}
	username.text = user;
	
	NSString *pass = [[NSUserDefaults standardUserDefaults] stringForKey: @"password_setting"];
	if(!pass){
		//pass = @"abc123";
	}
	password.text = pass;
	
	self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"mt-home-background_1.jpg"]];
	//scrollView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"mt-home-background_1.jpg"]];
	[self registerForKeyboardNotifications];
	//[[SrnStudentAppDelegate App] setJoinClicked:NO];
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
		
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(keyboardWasShown:)
												 name:UIKeyboardDidShowNotification object:nil];
	
    [[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(keyboardWasHidden:)
												 name:UIKeyboardDidHideNotification object:nil];
}

// Called when the UIKeyboardDidShowNotification is sent.
/*
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    if (keyboardShown)
        return;
	
    NSDictionary* info = [aNotification userInfo];
	
    // Get the size of the keyboard.
    NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
    CGSize keyboardSize = [aValue CGRectValue].size;
	
    // Resize the scroll view (which is the root view of the window)
    CGRect viewFrame = [scrollView frame];
    viewFrame.size.height -= keyboardSize.height;
    scrollView.frame = viewFrame;
	
    // Scroll the active text field into view.
    CGRect textFieldRect = [name frame];
    [scrollView scrollRectToVisible:textFieldRect animated:YES];
	[scrollView scroll
    keyboardShown = YES;
}
 */

- (void)keyboardWasShown:(NSNotification*)aNotification
{
	if (keyboardShown)
		return;
	
	self.view.backgroundColor = [UIColor grayColor];
	
	NSDictionary* info = [aNotification userInfo];
	CGSize kbSize = [[info objectForKey:UIKeyboardBoundsUserInfoKey] CGRectValue].size;
	CGRect bkgndRect = serveraddress.superview.frame;
	bkgndRect.size.height += kbSize.height;
	[serveraddress.superview setFrame:bkgndRect];
	[scrollView setContentOffset:CGPointMake(0.0, serveraddress.frame.origin.y - 40) animated:YES];
	scrollView.scrollEnabled = NO;
	keyboardShown = YES;
}


// Called when the UIKeyboardDidHideNotification is sent
- (void)keyboardWasHidden:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
	self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"mt-home-background_1.jpg"]];
    // Get the size of the keyboard.
    NSValue* aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
    CGSize keyboardSize = [aValue CGRectValue].size;
	
    // Reset the height of the scroll view to its original value
    CGRect viewFrame = [scrollView frame];
    viewFrame.size.height += keyboardSize.height;
    scrollView.frame = viewFrame;
	scrollView.scrollEnabled = YES;
    keyboardShown = NO;
}

- (BOOL) textFieldShouldReturn:(UITextField *)aTextField{
	if(aTextField == username){
		[username resignFirstResponder];
	}else if(aTextField == serveraddress){
		[serveraddress resignFirstResponder];
	}else if(aTextField == password){
		[password resignFirstResponder];
	}
	
	return YES;
}

@end
